﻿using Esint.JudicialAuction.BLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebJudicialAuction.admin.bases;
using Esint.Common;
using Esint.JudicialAuction.Model.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Esint.JudicialAuction.Model.Schedule;
using System.IO;
using Aspose.Cells;
using Esint.JudicialAuction.Model;

namespace WebJudicialAuction.admin.handler
{
    /// <summary>
    /// scheduleManagement 的摘要说明
    /// </summary>
    public class scheduleManagement : BaseHandler
    {
        Schedule_ShiftsService scheduleBll = new Schedule_ShiftsService();
        Schedule_UserService userBll = new Schedule_UserService();

        protected override AjaxResult BusinessHandleFunc(string req_type, Dictionary<string, string> dicData)
        {
            AjaxResult ajaxResult = new AjaxResult();

            switch (req_type)
            {
                default:
                    break;
                    //网信办自动排班方法
                case "TestOfficeSchedule":
                    {
                        if (dicData["AutoStartTime"].IsNullOrEmpty())
                        {
                            throw new DataValidException("排班开始时间不能为空");
                        }

                        if (dicData["AutoEndTime"].IsNullOrEmpty())
                        {
                            throw new DataValidException("排班结束时间不能为空");
                        }
                        scheduleBll.AutoCreateOfficeSchedule(dicData["AutoStartTime"], dicData["AutoEndTime"]);

                        ajaxResult.flag = AjaxResultFlag.Success;
                        ajaxResult.msg = AjaxMessage.OperationSuccess;

                        break;
                    }

                    //主列表查询方法
                case "GetSchedulePagedList":
                    {
                        var pageList = scheduleBll.GetSchedulePagedList(dicData["SearchStartTime"], dicData["SearchEndTime"], dicData["pgIndex"], dicData["pgSize"]);

                        ajaxResult.flag = AjaxResultFlag.Success;
                        ajaxResult.data = pageList;
                        ajaxResult.msg = AjaxMessage.SearchSuccess;

                        break;
                    }

                    //导出结果
                case "ExportSchedule":
                    {
                        var downloadUrl = CommonExtend.GetAppSetting("DownloadPath");
                        var saveDir = OwnContext.Server.MapPath(downloadUrl);
                        var templatePath = OwnContext.Server.MapPath(CommonExtend.GetAppSetting("ExportTemplatePath"));
                        var fileName = scheduleBll.GetExportScheduleList(dicData["AutoStartTime"], dicData["AutoEndTime"], saveDir, templatePath);
                        
                        string displayName = displayName = $"排班导出_{DateTime.Now.ToString("yyyy-MM-dd_HHmmsss")}.xlsx";

                        ajaxResult.flag = AjaxResultFlag.Success;
                        ajaxResult.data = fileName;
                        ajaxResult.msg = AjaxMessage.OperationSuccess;

                        break;
                    }

                    //中心自动排班方法
                case "AutoScheduleCenterWork":
                    {
                        if (dicData["AutoStartTime"].IsNullOrEmpty())
                        {
                            throw new DataValidException("排班开始时间不能为空");
                        }

                        if (dicData["AutoEndTime"].IsNullOrEmpty())
                        {
                            throw new DataValidException("排班结束时间不能为空");
                        }

                        scheduleBll.AutoCreateCenterSchedule(dicData["AutoStartTime"], dicData["AutoEndTime"]);

                        ajaxResult.flag = AjaxResultFlag.Success;
                        ajaxResult.msg = AjaxMessage.OperationSuccess;

                        break;
                    }

                    //查询单个用户排班情况
                case "GetUserScheduleList":
                    {
                        var list = scheduleBll.GetScheduleListByUserId(dicData["UserId"], dicData["pgIndex"], dicData["pgSize"], dicData["SearchStartTime"], dicData["SearchEndTime"]);

                        ajaxResult.flag = AjaxResultFlag.Success;
                        ajaxResult.data = list;
                        ajaxResult.msg = AjaxMessage.SearchSuccess;

                        break;
                    }

                    //获得中心编辑排班的数据
                case "LoadInfoForScheduleEdit":
                    {
                        //根据上班日期和类型查出该班可用人员
                        var userList = userBll.GetCanBeAutoList(dicData["WorkDate"], int.Parse(dicData["TypeCode"]));
                        var qyUseableUserList  = from t in userList select new { UserId = t.UserId, UserName = t.UserName };
                        List<object> useablePersons = new List<object>();
                        if (qyUseableUserList.FirstOrDefault() != null)
                        {
                            useablePersons.AddRange(qyUseableUserList.ToList());
                        }

                        var currentScheduleList = scheduleBll.GetScheduleList(dicData["WorkDate"], dicData["PlaceCode"], dicData["TypeCode"]);
                        
                        var qyCurrentSelectedPersonList = from t in currentScheduleList select new { UserId = t.UserId, UserName = t.UserName };

                        List<object> selectedPersons = new List<object>();
                        if (qyCurrentSelectedPersonList.FirstOrDefault() != null)
                        {
                            selectedPersons.AddRange(qyCurrentSelectedPersonList.ToList());
                        }

                        if (dicData["PlaceCode"] == "2")
                        {
                            useablePersons.Add(new { UserId = "xxx", UserName = "未安排中心人员" });
                        }
                        
                        ajaxResult.flag = AjaxResultFlag.Success;
                        ajaxResult.data = new { usedList = selectedPersons, freeList = useablePersons };
                        ajaxResult.msg = AjaxMessage.SearchSuccess;

                        break;
                    }

                    //获得网信办编辑排班的数据
                case "LoadInfoForOfficeScheduleEdit":
                    {
                        //根据上班日期和类型查出该班可用人员
                        var userList = userBll.GetCanBeAutoList(dicData["WorkDate"], int.Parse(dicData["TypeCode"]));
                        var qyUseableUserList = from t in userList select new { UserId = t.UserId, UserName = t.UserName };
                        List<object> useablePersons = new List<object>();
                        if (qyUseableUserList.FirstOrDefault() != null)
                        {
                            useablePersons.AddRange(qyUseableUserList.ToList());
                        }

                        var currentScheduleList = scheduleBll.GetScheduleList(dicData["WorkDate"], dicData["PlaceCode"], dicData["TypeCode"]);

                        var qyCurrentSelectedPersonList = from t in currentScheduleList select new { UserId = t.UserId, UserName = t.UserName };

                        List<object> selectedPersons = new List<object>();
                        if (qyCurrentSelectedPersonList.FirstOrDefault() != null)
                        {
                            selectedPersons.AddRange(qyCurrentSelectedPersonList.ToList());
                        }

                        if (dicData["PlaceCode"] == "2")
                        {
                            useablePersons.Add(new { UserId = "xxx", UserName = "未安排中心人员" });
                        }

                        ajaxResult.flag = AjaxResultFlag.Success;
                        ajaxResult.data = new { usedList = selectedPersons, freeList = useablePersons };
                        ajaxResult.msg = AjaxMessage.SearchSuccess;

                        break;
                    }

                    //日期转星期几
                case "GetDayOfWeekChinese":
                    {
                        var dateStr = dicData["dateValue"];

                        ajaxResult.flag = AjaxResultFlag.Success;
                        ajaxResult.data = CommonExtend.GetDayOfWeekChinese(dateStr);
                        ajaxResult.msg = AjaxMessage.SearchSuccess;
                        
                        break;
                    }

                case "SaveEditSchedule":
                    {
                        var typeCode = int.Parse(dicData["TypeCode"]);
                        var placeCode = int.Parse(dicData["PlaceCode"]);
                        OnceWork onceWork = new OnceWork((WorkType)typeCode, (WorkPlace)placeCode, Convert.ToDateTime(dicData["WorkDate"]));
                        var personIdListStr = dicData["FinallPersonsId"];
                        JArray jArray = JArray.Parse(personIdListStr);

                        if (jArray != null && jArray.Count() > 0)
                        {
                            var personList = userBll.GetUserListByIdList(jArray.ToList<string>());

                            onceWork.PersonList.AddRange(personList);
                        }

                        if (placeCode == 1) {
                            scheduleBll.ValidIfCanAutoSchedule(dicData["WorkDate"], dicData["WorkDate"], false);
                        }
                        
                        scheduleBll.SaveOnceWork(onceWork);
                        ajaxResult.flag = AjaxResultFlag.Success;
                        ajaxResult.msg = AjaxMessage.SaveSuccess;
                        break;
                    }

                    //换班
                case "SwitchPersonSchedule":
                    {
                        scheduleBll.SwithWorkForTwoPeople(JObject.Parse(dicData["switchObject1"]), JObject.Parse(dicData["switchObject2"]));

                        ajaxResult.flag = AjaxResultFlag.Success;
                        ajaxResult.msg = AjaxMessage.OperationSuccess;

                        break;
                    }

                    //导入排班方法
                case "ImportSchedules":
                    {
                        var fileName = dicData["fileName"];
                        var excelPath = OwnContext.Server.MapPath(CommonExtend.GetAppSetting("UploadPath")) + fileName;
                        if (!File.Exists(excelPath))
                        {
                            ajaxResult.flag = AjaxResultFlag.Failed;
                            ajaxResult.msg = AjaxMessage.NotFoundFile;
                        }
                        else
                        {
                            Workbook workbook = new Workbook(excelPath);
                            scheduleBll.ImportScheduleData(workbook);
                            
                            ajaxResult.flag = AjaxResultFlag.Success;
                            ajaxResult.msg = AjaxMessage.SaveSuccess;
                        }
                        break;
                    }
            }

            return ajaxResult;
        }

        
        
    }
}